package cn.com.yusys.yusp.uaa.security;

import cn.com.yusys.yusp.commons.security.SecurityUtils;
import cn.com.yusys.yusp.uaa.config.UaaConstants;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.validation.constraints.NotNull;
import java.util.Map;

/**
 * 认证相关工具类
 *
 * @author xiaodg
 */
public class AuthUtils {
    private static final Logger log = LoggerFactory.getLogger(AuthUtils.class);

    private AuthUtils() {

    }

    private static final int TOKEN_TYPE_BEARER_LENGTH = UaaConstants.BEARER_TOKEN_TYPE.length() + 1;


    public static Map getParsedAccessTokenMap() {
//        ServletRequestAttributes reqAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        if (reqAttributes == null) {
//            throw new RuntimeException("没有获取到request对象");
//        }

//        reqAttributes.getRequest().getHeader(UaaConstants.AUTHORIZATION_KEY);
//        if (authorization == null || authorization.length() <= TOKEN_TYPE_BEARER_LENGTH)
//            throw new RuntimeException("无效的Authorization");

        String accessToken = SecurityUtils.getCurrentUserToken();
        try {
            Map resMap = new ObjectMapper().readValue(JwtHelper.decode(accessToken).getClaims(), Map.class);
            resMap.put(UaaConstants.PARSED_TOKEN, accessToken);
            return resMap;
        } catch (Exception e) {
            log.error("Failed to parse token:{}", e.getMessage());
        }
        throw new RuntimeException("Token cannot be parsed correctly");
    }

    public static String getCurrentUserLogin(@NotNull Map<String, Object> parsedTokenMa) {
        Object loginCode = parsedTokenMa.get(UaaConstants.USER_NAME);
        if (loginCode != null) {
            return loginCode.toString();
        }
        return null;
    }

    public static String getCurrentUserLoginSYS(@NotNull Map<String, Object> parsedTokenMap) {
        Object sysId = parsedTokenMap.get(UaaConstants.SYS_ID);
        if (sysId != null) {
            return sysId.toString();
        }
        return null;
    }


    public static String getCurrentUserToken(@NotNull Map<String, Object> parsedTokenMap) {
        Object accessToken = parsedTokenMap.get(UaaConstants.PARSED_TOKEN);
        if (accessToken != null) {
            return accessToken.toString();
        }
        return null;
    }
}
